package cn.bellychang.leetcode.question019;

/**
 * @author ChangLiang
 * @date 2021/2/6
 */
public class Solution2 {
    public ListNode removeNthFromEnd(ListNode head, int n) {

        if (isNthNode(head, n)) {
            head = head.next;
        } else {
            ListNode prev = head;
            ListNode curr = head.next;
            while (curr != null) {
                if (isNthNode(curr, n)) {
                    prev.next = curr.next;
                    break;
                } else {
                    prev = curr;
                    curr = curr.next;
                }
            }
        }
        return head;
    }

    private boolean isNthNode(ListNode listNode, int n) {
        int number = 1;
        while (listNode.next != null) {
            number++;
            listNode = listNode.next;
        }
        return number==n;
    }
}
